package com.hmall.order.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmall.common.client.AddressAndUserClient;
import com.hmall.common.client.ItemClient;
import com.hmall.common.pojo.Order;
import com.hmall.common.status.OrderStatus;
import com.hmall.order.mapper.OrderDetailMapper;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.OrderDetail;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
@Component
@Slf4j
public class MQ {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    ItemClient itemClient;
    @Autowired
    AddressAndUserClient addressAndUserClient;
    @Autowired
    OrderDetailMapper orderDetailMapper;
    //    声明交换机
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "delay.queue",durable = "true"),
            exchange = @Exchange(name = "delay.direct",delayed = "true"),
            key = {"delay"}
    ))
    @GlobalTransactional
    public void  listenDelayedQueue(String orderId){
        try {
            log.info("接受到delay.queue的延迟消息:{}",orderId);
            Long orderid = Long.valueOf(orderId);
            Order order = orderMapper.selectById(orderid);
            if(order.getStatus()==1){
    //            更新订单状态和修改时间
                order.setStatus(OrderStatus.CANCEL_CLOSE);
                order.setUpdateTime(LocalDateTime.now());
                orderMapper.updateById(order);


    //            库存/销量回档
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("order_id",order.getId());
                OrderDetail orderDetail = orderDetailMapper.selectOne(queryWrapper);
                 itemClient.returnStock(orderDetail.getItemId(),orderDetail.getNum());
                log.info("取消订单完成");
            }
            else{
                log.info("消息已被消费");
                return;
            }
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
    }
}
